package com.ecsolutions.controller;


import com.ecsolutions.entity.finance_header_entity;
import com.ecsolutions.entity.finance_body_entity;
import com.ecsolutions.service.finance_Service;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/6/27.
 */
@Controller
public class finance_Controller{



//    //上传文件属性
//    private File finance_file;//上传的文件,名字必须和表单的name属性一致
//    private String uploadFileName;//文件名
//    private String uploadContextType;//文件类型

//    public void setFinance_file(File finance_file) {
//        this.finance_file = finance_file;
//    }
//    public void setUploadFileName(String uploadFileName) {
//        this.uploadFileName = uploadFileName;
//    }
//    public void setUploadContextType(String uploadContextType) {
//        this.uploadContextType = uploadContextType;
//    }

    //注入service
    @Autowired
    private finance_Service finance_service;

    public finance_Service getFinance_service() {
        return finance_service;
    }

    //    @GetMapping("/test")
//    public String getTestPage() {
//        return "test";
//    }

    @GetMapping("/financeInfo")
    public String getFinancePage(Model model_header, Model model_body ) {
        model_header.addAttribute("finance_header_entity", new finance_header_entity());
        model_body.addAttribute("finance_body_entity", new finance_body_entity());
        model_header.addAttribute("finance_info", finance_service.getPopupInfo());
        model_body.addAttribute("finance_info", finance_service.getPopupInfo());
        return "financeInformation";
    }

//    @ResponseBody
//    @RequestMapping(value = "/finance_insertCheck",method = RequestMethod.POST,consumes = "application/json",produces = "application/json")
//    public String findAll(@RequestBody Map<String, Object> map){;
//        String custcode = map.get("custcode").toString();
//
//        return insert_result;
//    }

    /**
     * 区域文件上传
     * @return
     * @throws Exception
     */
    @PostMapping("/financeInfo")
    public String upload(@ModelAttribute finance_header_entity finance_header_entity ,@RequestParam String custcode, Model model_header, @ModelAttribute finance_body_entity finance_body_entity , BindingResult result, Model model_body)throws Exception{
        model_header.addAttribute("finance_header_entity", finance_header_entity);
        model_body.addAttribute("finance_body_entity", finance_body_entity);
        model_header.addAttribute("finance_info", finance_service.getPopupInfo());
        model_body.addAttribute("finance_info", finance_service.getPopupInfo());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String insert_result;
        insert_result = finance_service.insertCheck(custcode);
        Integer i_balance_body = 1;
        Integer insert_flag = 0;
        //获取客户端上传的文件(使用属性驱动+fileUpload拦截器)

        //存放结果集map
        Map<String,Object> resultMap = new HashMap<String,Object>();
//        //存放finance_entity的list
//        List<finance_header_entity> financeHeaderList = new ArrayList<finance_header_entity>();
//        List<finance_header_entity> financeBodyList = new ArrayList<finance_header_entity>();

        try {
            //解析excel
            //1.读取文件输入流
            InputStream is = new FileInputStream("D:\\财务导入模板.xls");
            //2.创建Excel工作簿文件(包含.xsl和.xslx格式)
            Workbook wb = WorkbookFactory.create(is);
            //3.打开需要解析的Sheet工作表
            for (int i =0 ; i < wb.getNumberOfSheets(); i++) {
                Sheet sheet = wb.getSheetAt(i);
                //4.遍历工作表对象（本质是个行的集合）,读取每一行
                if (sheet.getSheetName().equals("ADS_资产负债表表头") || sheet.getSheetName().equals("ADS_损益表表头") || sheet.getSheetName().equals("ADS_现金流量表表头")) {
                    for (Row row : sheet) {
                        //                //跳过第一行
                        //                if (row.getRowNum() == 0) {
                        //                    continue;
                        //                }
                        //另外，一般第一列都标识列，如果第一个格没数据，则认为该行数据无效，要跳过
                        //注意：getStringCellValue()读取的格必须是文本，否则抛异常
                        if (StringUtils.isNotBlank(row.getCell(0).getStringCellValue())) {
                            if (row.getCell(0).getStringCellValue().equals("报表名称")) {
                                finance_header_entity.setAuditoffice(row.getCell(2).getStringCellValue());
                            }
                            if (row.getCell(0).getStringCellValue().equals("报表编号")) {
                                finance_header_entity.setReportno(row.getCell(2).getStringCellValue());
                            }
                            if (row.getCell(0).getStringCellValue().equals("客户编号")) {
                                finance_header_entity.setCustcode(row.getCell(2).getStringCellValue());
                            }
                            if (row.getCell(0).getStringCellValue().equals("起始日期")) {
                                finance_header_entity.setReportdate(sdf.parse(row.getCell(2).getStringCellValue()));
                            }
                            if (row.getCell(0).getStringCellValue().equals("截止日期")) {
                                finance_header_entity.setReportenddate(sdf.parse(row.getCell(2).getStringCellValue()));
                            }
                            if (row.getCell(0).getStringCellValue().equals("报表类型")) {
                                finance_header_entity.setTypeid((int)(row.getCell(2).getNumericCellValue()));
                            }
                            if (row.getCell(0).getStringCellValue().equals("审计员")) {
                                finance_header_entity.setAuditofficer(row.getCell(2).getStringCellValue());
                            }
                            if (row.getCell(0).getStringCellValue().equals("审计日期")) {
                                finance_header_entity.setAudittime(sdf.parse(row.getCell(2).getStringCellValue()));
                            }
                        }
                    }
//                    financeHeaderList.add(finance_header_entity);
                    if (insert_result.equals("0")) {
                        insert_flag = 1;
                    }
                    if (!(result.hasErrors())) {
                        if (insert_flag == 1) {
                            finance_service.saveFinanceHeaderEntity(finance_header_entity);
                        }
                    }
                }

                if (sheet.getSheetName().equals("ADS_资产负债表") || sheet.getSheetName().equals("ADS_损益表") || sheet.getSheetName().equals("ADS_现金流量表")) {
                    for (Row row : sheet) {
                        if (StringUtils.isNotBlank(row.getCell(0).getStringCellValue())) {
                            if (row.getRowNum() == 0) {
                                continue;
                            }
                            String reportno = finance_header_entity.getReportno();
                            finance_body_entity.setReportno(reportno);
                            finance_body_entity.setSeqno(i_balance_body);
                            finance_body_entity.setTypeid(row.getCell(0).getStringCellValue());
                            finance_body_entity.setOrigvalue(row.getCell(2).getNumericCellValue());
                            finance_body_entity.setEndvalue(row.getCell(3).getNumericCellValue());
                            i_balance_body++;
//                            financeBodyList.add(finance_header_entity);
                            if (!(result.hasErrors())) {
                                if (insert_flag == 1) {
                                    finance_service.saveFinanceBodyEntity(finance_body_entity);
                                }
                            }
                        }
                    }
                }
            }

//            //调用service保存数据
//            for (finance_header_entity finance_header : financeHeaderList){
//                finance_service.saveFinanceHeaderEntity(finance_header);
//            }
//            for (finance_header_entity finance_body : financeBodyList){
//                finance_service.saveFinanceBodyEntity(finance_body);
//            }

            //解析成功
            resultMap.put("result", true);

            //关流
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            //解析失败
            resultMap.put("result", false);
        }
//        //将装有结果集的map压入栈顶
//        pushToValueStack(resultMap);
//        //返回json类型
//        return JSON;
        return "financeInformation";
    }

    //根据客户号custcode显示财务表头信息
    @ResponseBody
    @RequestMapping(value = "/financeHeaderInfo_Search",method = RequestMethod.POST,consumes = "application/json",produces = "application/json")
    public List<finance_header_entity> findByCustcode(@RequestBody Map<String, Object> map){
        String custcode = map.get("custcode").toString();
        List<finance_header_entity> result = finance_service.financeHeaderInfoSearch(custcode);
        return result;
    }

    //根据报表编号reportno显示财务表体信息
    @ResponseBody
    @RequestMapping(value = "/financeBodyInfo_Search",method = RequestMethod.POST)
    public List<finance_body_entity> findByReportno(@RequestBody Map<String, Object> map){
        String custcode = map.get("custcode").toString();
        List<finance_body_entity> result = new ArrayList<finance_body_entity>();
        List<String> reportno_bodyList = finance_service.getReportno(custcode);
        for (String reportno_body : reportno_bodyList) {
            for(int i = 0;i < (finance_service.financeBodyInfoSearch(reportno_body)).size();i++) {
                result.add(finance_service.financeBodyInfoSearch(reportno_body).get(i));
            }
        }
        return result;
    }

}
